import {createApp} from 'vue';
import App from './App.vue';
import router from './router';
//导入SVG依赖库，可以在页面上显示SVG图片（此处为新增）
import 'virtual:svg-icons-register';
//引用ElementPlus的CSS文件，否则MacOS系统会出现控件丢失样式
import 'element-plus/dist/index.css';
//导入ElementUI组件库
import ElementPlus from 'element-plus';
//为了让日历控件每周从星期一开始，所以要导入简体中文场景
import locale from 'element-plus/es/locale/lang/zh-cn';
//为了可以使用ElementPlus自带的图标库
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
//导入JQuery库，因为Ajax用起来非常方便，支持同步和异步的Ajax请求
import $ from 'jquery';
//导入ElementUI的消息通知组件，下面封装全局Ajax的时候处理异常的时候需要弹出通知
import {ElMessage} from 'element-plus';
import VueNativeSock from 'vue-native-websocket-vue3'
import  jsPDF from "jspdf";
import html2canvas from 'html2canvas';


function isSplit(nodes, index, pageHeight) {
    if (
        nodes[index].offsetTio + nodes[index].offsetHeight < pageHeight &&
        nodes[index + 1] &&
        nodes[index + 1].offsetTop + nodes[index + 1].offsetHeight > pageHeight
    ) {
        return true;
    }
    return false;
}


const app = createApp(App);
app.config.globalProperties.getPdf = function () {
    var title = this.htmlTitle;
    let ST = document.documentElement.scrollTop || document.body.scrollTop;
    let SL = document.documentElement.scrollTop || document.body.scrollLeft;
    document.documentElement.scrollTop = 0;
    document.documentElement.scrollLeft = 0;
    document.body.scrollTop = 0;
    document.body.scrollLeft = 0;
    const A4_WIDTH = 592.28;  // A4 width in points
    const A4_HEIGHT = 841.89; // A4 height in points

    let imageWrapper = document.querySelector('#pdfDom'); // Get the DOM element

    var title = imageWrapper.getAttribute('name'); // PDF title

    let pageHeight = (imageWrapper.scrollWidth / A4_WIDTH) * A4_HEIGHT;

    let labelListID = imageWrapper.querySelectorAll('p');// Get all paragraph elements


    for (let i = 0; i < labelListID.length; i++) {
        let multiple = Math.ceil((labelListID[i].offsetTop + labelListID[i].offsetHeight) / pageHeight);
        if (isSplit(labelListID, i, multiple * pageHeight)) {
            let divParent = labelListID[i].parentNode;
            let newNode = document.createElement('div');
            newNode.className = 'emptyDiv';
            newNode.style.backgroundColor = '#ffffff'; // Set background to white

            // Set the height of the new div to fill the remaining space on the page
            let _H = multiple * pageHeight - (labelListID[i].offsetTop + labelListID[i].offsetHeight);
            newNode.style.height = _H + 30 + 'px'; // Adding some extra space
            newNode.style.width = '100%';

            // Insert the new empty div before the current label
            let next = labelListID[i].nextSibling;
            if (next) {
                divParent?.insertBefore(newNode, next);
            } else {
                divParent.appendChild(newNode);
            }
        }
    }
    this.$nextTick(() => {
        // nextTick ensures that the current DOM updates are completed before executing the next operation

        html2canvas(imageWrapper, {
            allowTaint: true,
            taintTest: false,
            useCORS: true,
            dpi: window.devicePixelRatio * 4, // Increase DPI to 4x for higher resolution rendering
        }).then(canvas => {
            let pdf = new jsPDF('p', 'mm', 'a4');  // A4 size in mm: 210mm x 297mm

            let ctx = canvas.getContext('2d');
            const a4w = 210; // A4 width in mm
            const a4h = 297; // A4 height in mm
            let imgHeight = Math.floor((a4h * canvas.width) / a4w);
            let renderedHeight = 0;

            while (renderedHeight < canvas.height) {
                let page = document.createElement('canvas');
                page.width = canvas.width;
                page.height = Math.min(imgHeight, canvas.height - renderedHeight);
                page.getContext('2d')?.putImageData(
                    ctx.getImageData(
                        0,
                        renderedHeight,
                        canvas.width,
                        Math.min(imgHeight, canvas.height - renderedHeight)
                    ),
                    0,
                    0
                );
                pdf.addImage(
                    page.toDataURL('image/jpg', 1.0), 'JPEG', 10, 10, a4w, Math.min(a4h, page.height * (a4w / page.width))
                );
                renderedHeight += imgHeight;
                if (renderedHeight < canvas.height) pdf.addPage();
            }
            pdf.save(`${title}.pdf`);
        });
    });

}
//后端项目的URL根路径
let baseUrl = 'https://localhost:7700/his-api';
//Minio服务器地址
let minioUrl = 'http://localhost:9090/his';
app.use(router);

//把ElementUI组件库整合到VUE框架上
app.use(ElementPlus, {
    locale
});
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.use(VueNativeSock, 'wss://localhost:7700/his-api/socket', {
    format: 'json',
    reconnection: true
})

app.config.globalProperties.$baseUrl = baseUrl; //设置全局变量$baseUrl

app.config.globalProperties.$minioUrl = minioUrl;
//封装全局Ajax公共函数
app.config.globalProperties.$http = function (url: string, method: string, data: JSON, async: boolean, fun: Function) {
    $.ajax({
        url: baseUrl + url,
        type: method,
        dataType: 'json',
        contentType: 'application/json',
        //上传的数据被序列化（允许Ajax上传数组）
        traditional: true,
        xhrFields: {
            //允许Ajax请求跨域
            withCredentials: true
        },
        headers: {
            token: localStorage.getItem('token')
        },
        async: async,
        data: JSON.stringify(data),
        success: function (resp: any) {
            if (resp.code == 200) {
                fun(resp);
            } else {
                ElMessage.error({
                    message: resp.msg,
                    duration: 1200
                });
            }
        },
        error: function (e: any) {
            //ajax有语法错误的时候
            if (e.status == undefined) {
                ElMessage.error({
                    message: '前端页面错误',
                    duration: 1200
                });
            } else {
                let status = e.status;
                //没有登陆体检系统
                if (status == 401) {
                    if (url.startsWith('/front')) {
                        router.push({
                            name: 'FrontIndex'
                        });
                    } else {
                        router.push({
                            name: 'MisLogin'
                        });
                    }
                } else {
                    //后端没有运行，提交的数据有误，或者没有连接上后端项目
                    if (!e.hasOwnProperty('responseText')) {
                        ElMessage.error({
                            message: '后端项目没有启动，或者HTTP请求类型以及参数错误',
                            duration: 1200
                        });
                    } else {
                        ElMessage.error({
                            message: e.responseText,
                            duration: 1200
                        });
                    }
                }
            }
        }
    });
};
//封装用于判断用户是否具有某些权限的公共函数
app.config.globalProperties.isAuth = function (permission: string[]) {
    const permissions: string | null = localStorage.getItem('permissions');
    if (permissions) {
        let flag = false;
        for (let one of permission) {
            if (permissions.includes(one)) {
                flag = true;
                break;
            }
        }
        return flag;
    } else {
        return false;
    }
};
app.mount('#app');
